import Taro from '@tarojs/taro'
import {View, Text, RichText} from '@tarojs/components'
import {connect} from '@tarojs/redux'
import {unitConvert, arrayRemove} from '../../utils/utils';
import moment from 'moment'
import {AtTag, AtButton} from 'taro-ui'
import withShare from "../../components/share/withShare";

import './index.less'

@connect(state => ({
  project: state.project,
}))
@withShare()
export default class Index extends Taro.Component {

  config = {
    navigationBarTitleText: '详情',
  }

  constructor() {
    super(...arguments)

    const {id = 0} = this.$router.params
    const favArray = Taro.getStorageSync('favs').split(',')
    const faved = favArray.includes(id.toString())
    this.state = {
      faved,
      favArray,
    }
  }

  componentDidMount() {
    const {id = 0} = this.$router.params
    this.props.dispatch({
      type: 'project/get',
      payload: id,
    });
  }

  switchFav = (id) => {
    let {faved, favArray} = this.state

    faved = !faved
    if (faved) {
      Taro.showToast({
        title: '已关注',
        icon: 'success',
        duration: 1000,
      });
      if (!favArray.includes(id)) {
        favArray.push(id)
        Taro.setStorageSync('favs', favArray.join(','))
      }
    } else {
      Taro.showToast({
        title: '已取消关注',
        icon: 'none',
        duration: 1000,
      });
      arrayRemove(favArray, id.toString())
      Taro.setStorageSync('favs', favArray.join(','))
    }
    this.setState({
      faved,
      favArray,
    })
  }

  download = (url) => {
    if (!url) {
      Taro.showToast({
        title: '没有文件',
        icon: 'none',
        duration: 1000,
      });
      return;
    }

    Taro.showLoading({
      title: '处理中...',
    });
    Taro.downloadFile({
      url,
      success: function (res) {
        let tempFilePath = res.tempFilePath;

        // open
        Taro.openDocument({
          filePath: tempFilePath,
          success: function(res) {
            console.log('打开文档成功')
          },
          fail (res) {
            console.log(res.errMsg);
            Taro.showToast({
              title: '打开失败',
              icon: 'none',
              duration: 1000,
            });
          },
          complete () {
            Taro.hideLoading();
          }
        });

        // save
        /*Taro.saveFile({
          tempFilePath,
          success (res) {
            console.log('下载成功，保存路径：' + res.savedFilePath);
            Taro.showToast({
              title: '下载成功',
              icon: 'success',
              duration: 1000,
            });
          },
          fail (res) {
            console.log(res.errMsg);
            Taro.showToast({
              title: '下载失败',
              icon: 'none',
              duration: 1000,
            });
          },
          complete () {
            Taro.hideLoading();
          }
        });*/
      }
    });
  }

  call = () => {
    Taro.makePhoneCall({
      phoneNumber: '18352513572',
      success: function (res) {
        console.log("接口调用成功返回的回调")
      },
      fail: function (res) {
        console.log("接口调用失败返回的回调")
      },
      complete: function (res) {
        console.log("接口调用结束的回调函数（调用成功、失败都会执行）")
      }
    })
  }

  toHome = () => {
    Taro.switchTab({url: '/pages/home/index'});
  }

  render() {
    const {project: {item}} = this.props
    const {faved} = this.state
    const date = moment(item.updated_at).format('YYYY-MM-DD')
    const priceUnit = unitConvert(item.price)
    const tagArray = item.tags ? item.tags.split(',') : []
    const content = item.content && item.content.replace(/width:\s*auto/gi, 'max-width:100%')

    return (
      <View className='container'>
        <View className='img-wrapper'>
          <Image mode='widthFix' className='img' src={item.img}/>
        </View>
        <View className='title-wrapper'>
          <Text className='title'>{item.name}</Text>
          <View className='meta'>
            <View className='tags-wrapper'>
              {
                tagArray.length && tagArray.map(val => <AtTag key={val} size='small' customStyle={{marginRight: '4Px', color: '#0cf'}}>{val}</AtTag>)
              }
            </View>
            <AtButton openType='share' size='small' customStyle={{color: '#fff', background: '#8A9DEA', border: 'none'}}>
              <Text className="iconfont icon-fenxiang1"/>
              <Text className="text">分享</Text>
            </AtButton>
          </View>
          <View className='meta'>
            <Text className='price-wrapper'>
              <Text class='price'>{item.negotiable ? '面议' : priceUnit.num}</Text>
              {
                !item.negotiable && <Text class='unit'>{priceUnit.unit}</Text>
              }
            </Text>
          </View>
        </View>
        <View className='panel'>
          <View className='head'>
            <Text class='title'>基本信息</Text>
          </View>
          <View className='body with-padding base-info'>
            <View class='attr'>
              <Text class='attr-key'>项目编号</Text>
              <Text class='attr-value'>{item.no}</Text>
            </View>
            <View class='attr'>
              <Text class='attr-key'>项目分类</Text>
              <Text class='attr-value'>{item.cname1}{item.cname2}</Text>
            </View>
            <View class='attr'>
              <Text class='attr-key'>所在省市</Text>
              <Text class='attr-value'>{item.province_name}{item.city_name}</Text>
            </View>
            <View class='attr'>
              <Text class='attr-key'>发布日期</Text>
              <Text class='attr-value'>{date}</Text>
            </View>
            <View class='attr'>
              <Text class='attr-key'>项目位置</Text>
              <Text class='attr-value'>{item.address}</Text>
            </View>
          </View>
        </View>
        {/*<View class='contact'>
          <Text class='attr-key'>电话☎️</Text>
        </View>*/}
        <View className='panel'>
          <View className='head'>
            <Text class='title'>详细信息</Text>
          </View>
          <View className='body with-padding'>
            <RichText nodes={content}/>
          </View>
        </View>
        <View className='foot'>
          <View className='icon-wrapper'>
            {
              faved
                ? <Text className="iconfont icon-favorite" onClick={this.switchFav.bind(this, item.id)}/>
                : <Text className="iconfont icon-favoff" onClick={this.switchFav.bind(this, item.id)}/>
            }
            <Text className="iconfont icon-xiazai3" onClick={this.download.bind(this, item.download_url)}/>
            <Text className="iconfont icon-dianhua" onClick={this.call}/>
            <Text className="iconfont icon-home_fill_light" onClick={this.toHome}/>
          </View>
        </View>
      </View>
    )
  }
}